<template>
  <div class="body">
        <div style="border-right: 1px solid #e2e2e2 ; width: 17.205vw; height: 95vh;" >
            <div class="search">
                <el-input style=" width:70%; height: 90%; margin :5% 5% 0% 0%; " @input="uidCheck" maxlength=20 v-model="searchData" placeholder="输入uid添加新朋友\群聊"></el-input>
                <div class="search-image-div" @click="searchUid" >
                    <el-image class="search-image" :src="searchImage"/>
                </div>
            </div>
            <div class="list">
                <div @click="selectItem(p)" id="list-item" v-for="(p,index) in chatList" :key="index" class="list-item">
                    <!-- 未读消息提示 -->
                    <el-badge style=" width:25%; height: 100%;" :value="p.unreadmsg" :hidden="p.unreadmsg==0">
                        <el-image class="image-head" :src="p.headimage"/>
                    </el-badge>
                    <div class=" list-item-text">
                        <div class="list-item-text-line"  style=" height:50%; margin-bottom:5%; font-weight: bold; font-size:1vw" >{{p.name}}</div>
                        <div class="list-item-text-line"  v-show="p.chathistory.isimage">{{p.chathistory.sendusername}}：[图片]</div>
                        <div class="list-item-text-line"  v-show="!(p.chathistory.isimage)">{{p.chathistory.sendusername}}：{{p.chathistory.data}}</div>
                    </div>
                </div>
                
            </div>
        </div>
        <div class="message">
            <div v-if="$store.state.notInit" style="width: 75.395vw; height: 95vh;
             display: flex; justify-content: center; align-items: center; " >
             <div class="not_init" /></div>
            <ChatMessage v-if="!$store.state.notInit" />
        </div>
        <el-dialog :visible.sync="dialogVisible" width="30%">
        <div v-if="!isNull">
            <div style="display: flex; justify-content: center; align-content: center;">
            <div :style="{backgroundImage:`url(${this.searchDataHeadImage})`}" class="search-data-head-image" />
            <p class="search-data-head-name">{{searchDataHeadName}}</p>
        </div>
        <hr/>
        <div @click="addUid" class="add-button">
            {{addMsg}}
        </div>
        <div style="height: 2vh" />
        </div>
        <div v-if="isNull" class="no-search-data">
            此UID未找到任何信息哦
            <div @click="dialogVisible = !dialogVisible;" class="add-button">
                确定
            </div>
        </div>
        
        </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import ChatMessage from './ChatMessage'
export default {
    components:{
        ChatMessage
    },
    mounted(){
    },
    data(){
        return{   
            isGroup:false, // 是否为群
            isNull:false, // 是否为空uid
            searchDataHeadImage:'', // 显示搜索的结果
            searchDataHeadName:'', // 显示搜索的结果
            searchDataUid:'', // 显示搜索的结果
            addMsg:"", // 搜索后根据结果渲染按钮内容
            dialogVisible:false,  // 搜索弹窗
            searchData:'', // 搜索内容(uid)
            searchImage:require('@/assets/search.png'), // 搜索图标
        }
    },
    computed:{
        chatList(){
            return this.$store.state.chatList
        }
    },
    watch: {
        dialogVisible(newVal, oldVal) {
            if (!newVal && oldVal) {
                // 当 dialogVisible 从 true 变为 false时将内容都置空
                this.searchDataHeadImage = '';
                this.searchDataHeadName = '';
                this.searchDataUid='';
                this.searchData='';
                this.isGroup=false;
            }
        }
    },
    methods:{
        selectItem(p){
            // 更新聊天未读消息数量并清空该对象所有未读消息提示
            this.$store.dispatch("updateChatUnreadMsg",
            {vue:this,uid:p.uid,unreadmsg:p.unreadmsg,isGroup:p.chathistory.groupuid>0}) 
            if(p.uid==this.$store.state.chatObjectUid){
                return
            }
            this.$store.commit("INIT_MESSAGE_WINDOWS") // 撤销聊天窗口占位图
            this.$store.commit("UPDATE_CHAT_OBJECT",{uid:p.uid,
                name:p.name,headImage:p.headimage,isGroup:p.chathistory.groupuid>0,exist:p.exist});
            this.$store.commit("INIT_CHAT_MSG",[]) // 清空聊天内容
            this.$store.commit("INIT_MESSAGE_OLDSCROLL_HEIGHT"); // 清空旧聊天对象的高度数据
            this.$store.dispatch('getChatHistory',{vue:this,uid:p.uid,isGroup:p.chathistory.groupuid>0}); // 请求聊天记录数据

        },
        //addUid方法执行结果的回调方法
        addUidCallback(response){
            const lastData = this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(response.data)).toObject();

            this.$store.commit("DELETE_TASK",lastData.taskid)
            this.dialogVisible=!this.dialogVisible
            this.$message({
                    message:'发送成功!',
                    type:'success'
                })
        },
        // 发出添加好友或者申请入群消息
        addUid(){
            if(this.searchDataUid==this.$store.state.userUid){
                this.$message({
                    message:'无法添加自己为好友',
                    type:'warning'
                })
                return
            }
            if(this.$store.commit("IS_ADDED",this.searchDataUid)){
                this.$message({
                    message:'你已经是该用户的好友或该群聊的成员了',
                    type:'warning'
                })
                return
            }
            // 将对应任务添加进任务列表映射中,注意这里的任务id是1开始的，避免有些时候默认值是0的情况
            this.$store.commit('ADD_TASK',this.addUidCallback.bind(this))

            let proto =new this.$protobufClass.PackageInfo();
            let data;
            // 确定是哪个对象，填充内容
            if(this.isGroup){
                data = new this.$groupInfo.GroupInfo();
                data.setUid(this.searchDataUid); // 填充uid
                proto.setGroupinfo(data)
            }else{
                data = new this.$accountNumber.AccountNumber();
                data.setUid(this.searchDataUid); // 填充uid
                proto.setAccountnumber(data)
            }
            // 也可以不用token,websocket其实没这个必要都加上。传uid也可以
            proto.setToken(localStorage.getItem("token"));
            proto.setCallbackid(2); // 后端的处理事件id
            proto.setTaskid(this.$store.state.taskId); // 自己的任务id
            proto=proto.serializeBinary();
            this.$webSocketTools.send(this,proto)
        },
        searchUid(){
            if(this.searchData.length==0){
                this.$message({
                    message:'请输入要搜索的uid',
                    type:'warning'
                })
            }else{
                this.dialogVisible=!this.dialogVisible
                
                axios.get(`/accountNumbers/searchUid/${this.searchData}`,{
                    headers:{
                        'Authorization':localStorage.getItem('token'),
                        'Content-Type':'application/x-protobuf'
                    },
                    responseType:'arraybuffer'
                }).then(res=>{
                    const lastData = this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(res.data)).toObject();
                    if(lastData.code==200){
                        if(lastData.accountnumber!=null){
                            this.isNull=false;
                            this.searchDataHeadName=lastData.accountnumber.name;
                            this.searchDataUid=lastData.accountnumber.uid;
                            this.searchDataHeadImage= this.getImageType(lastData.accountnumber.image)
                            this.addMsg="添加好友"// 这里根据获得的数据做区分加好友还是加群
                        }else if(lastData.groupinfo!=null){
                            this.isGroup=true;
                            this.isNull=false;
                            this.searchDataHeadName=lastData.groupinfo.name;
                            this.searchDataUid=lastData.groupinfo.uid;
                            this.searchDataHeadImage= this.getImageType(lastData.groupinfo.headimage)
                            this.addMsg="加入群"// 这里根据获得的数据做区分加好友还是加群
                        }else{
                            this.isNull=true;
                        }
                    }else{
                        this.isNull=true;
                    }
                }).catch(err=>{
                    this.isNull=true;
                    console.log(err)
                     this.$message({
                            message:err.message,
                            type:'error'
                        })
                })
            }

        },
        uidCheck(value){
            this.searchData = value.replace(/[^0-9]/g, '');
        },
        getImageType(imageString){
            if(imageString.startsWith('/9j/')){
                return `data:image/jpg;base64,${imageString}`
            }else if(imageString.startsWith('iVBOR')){
                return `data:image/png;base64,${imageString}`
            }else{
                return null
            }
        }
    }

}
</script>


<style scoped>
.not_init{
    width: 30%;
    height: 50%;
    background-image: url('../../assets/list_logo.png');
    background-size: contain;
    background-repeat: no-repeat;
}
.add-button:hover{
    cursor: pointer;
}
.no-search-data{
    display: flex; 
    flex-direction:column ;
    justify-content: center;
    align-items: center;
    font-size: 1.5vw;
}
.add-button{
    display: flex; 
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    width: 5.5vw;
    height: 2.5vw;
    font-size: 1vw;
    border-radius: 5px;
    color: #ffffff;
    margin: 0 auto;
    margin-top: 8%;
    background-color: #35d750;
}
.search-data-head-image{
    background-size: cover;
    background-repeat: no-repeat;
    width: 5vw;
    height: 10vh;
    border-radius: 10px;
    margin-left: 5%;
}
.search-data-head-name{
    width: 18vw;
    height: 5vh;
    font-size: 1.5vw;
    margin-left: 3%;
}
#list-item:hover{
  /* 鼠标悬浮时给手展示的效果 */
  cursor: pointer;
  /* 选中时背景色改变 */
  background-color: #cacacc;
}
.search-image-div:hover{
    cursor: pointer;
    background-color: #e2e2e2;
}
.image-head{
    border-radius: 5px;
    background-size: cover;
    background-repeat: no-repeat;
    width:100%;
    height: 100%;
}
.search-image{
    width:35%;
    height: 60%;
    background-size: contain;
    background-repeat: no-repeat; 
    margin: 10% 0% 0% 30%;
}
.search-image-div{
    border-radius: 10px;
    border:1px solid #ABACAF ;
    background-color: #ffffff;
    width:20%;
    height: 36%;
    margin-top:8%; 
}
.list-item-text-line{
    white-space: nowrap;     /* 禁止换行 */
    overflow: hidden;        /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 显示省略号 */
    width: 100%; 
    height: 45%; 
}
.list-item-text{
    width: 72%;
    height: 100%; 
    padding: 0% 0% 0% 3%;
}

.list-item{
    border-radius: 5px;
    width: 92%;
    height: 8%;
    display:flex;
    padding: 4% 0% 4% 5% ;
}
.list{
    border-radius: 5px 0px 0px 0px;
    overflow-y: scroll;
    width: 100%;
    height: 90%;
    background-color: #f2f2f7;
}
.body{
    display: flex;
    width: 92.6vw;
    height: 95.5vh;
    margin: 0vh 0vh 0vh 1vw;
    border-radius: 30px 30px 0px 30px;
}
.message{
    width: 75.395vw;
    height: 95vh;
}
.search{
    display: flex;
    background-color:  #F5F6FA;
    width: 100%;
    height: 10%;
}
</style>